package fi.hut.soberit.agilefant.reporting.controller;

import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PropertyComparator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.sun.jersey.api.client.WebResource;

import fi.hut.soberit.agilefant.model.export.BacklogInfoCollectionTO;
import fi.hut.soberit.agilefant.model.export.BacklogInfoTO;
import fi.hut.soberit.agilefant.reporting.communication.RemoteCommunicationBuilder;

@Controller
public class BacklogSelectionController {
  
  @Autowired
  private RemoteCommunicationBuilder rcb;

  @RequestMapping("products.htm")
  public ModelAndView getProducts(HttpServletRequest req, HttpServletResponse resp) {
    return getBacklogs("/product/list", "Product");
  }
  
  @RequestMapping("projects.htm")
  public ModelAndView getProjects(@RequestParam("productId") Integer productId) {
    return getBacklogs("/product/" + productId + "/projects", "Project");
  }

  @RequestMapping("iterations.htm")
  public ModelAndView getIterations(@RequestParam("projectId") Integer projectId) {
    return getBacklogs("/project/" + projectId + "/iterations", "Iteration");
  }
  
  @SuppressWarnings("unchecked")
  private ModelAndView getBacklogs(String url, String pageTitle) {
    ModelAndView mv = new ModelAndView("backlogs");
    WebResource res = rcb.getResourceForUrl(url);
    List<BacklogInfoTO> backlogs = res.get(BacklogInfoCollectionTO.class).getBacklog();
    Collections.sort(backlogs, new PropertyComparator("objectId", true, true));
    mv.addObject("backlogs", backlogs);
    mv.addObject("pageTitle", pageTitle);
    return mv;
  }
  
}
